const shell = require('shelljs')
const fs = require('fs')
const join = require('path').join
module.exports = (socket) => {
  socket.on('shell', (data) => {
    console.log(data)
    let {cmd, html} = data
    let txt = ''
    fs.writeFile(join(__dirname, './shell.sh'), cmd, (err) => {
      if (err) return socket.emit('result', {err})
      let child = shell.exec(cmd, { async: true })
      child.stdout.on('data', function (data) {
        /* ... do something with data ... */
        console.log('stdout:', data)
        let ht = data.replace('\n', '<br>')
        txt = txt + ht
        fs.writeFile(join(__dirname, './shell.txt'), txt)
        socket.emit('result', { html: html + `<p clsss="shell">${cmd}</p>` + txt })
      })
      child.stderr.on('data', function (data) {
        /* ... do something with data ... */
        txt = txt + data + '<br>'
        fs.writeFile(join(__dirname, './shell.txt'), txt)
        socket.emit('result', { html: data })
      })
    })
  })
}
